import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/components/singer_card.dart';
import 'package:flutter_app/model/user_model.dart';
import 'package:flutter_app/services/user_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class SingerPage extends StatefulWidget {
  SingerPage({Key key}) : super(key: key);

  @override
  _SingerPageState createState() => _SingerPageState();
}

class _SingerPageState extends State<SingerPage> with AutomaticKeepAliveClientMixin{
  EasyRefreshController _controller;

  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  List<UserItem> _userList = UserList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg = '';

//  String userType = 'DQ_SINGER';
  String userType = '';

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
    _scrollController = ScrollController();
    _getSingers();
  }

  @override
  void dispose() {
    _controller.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future _getSingers({bool push = false}) async {
    try {
      //获取数据
//      Map<String, dynamic> result = await UserService()
//          .getUsers(page: page, limit: limit, type: userType);
      Map<String, dynamic> result;
      String data = await rootBundle.loadString("assets/data/singer.json");
      result = jsonDecode(data);
      //将数据转为实体类
      UserList songListModel = UserList.fromJson(result['data']);
      setState(() {
        hasMore = page * limit < result['total'];
        page++;
        if (push) {
          _userList = songListModel.list;
        } else {
          _userList.addAll(songListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  //上拉加载
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 1;
    await _getSingers();
    _controller.resetLoadState();
  }

  //下拉刷新
  Future _onLoad() async {
    if (hasMore) {
      await _getSingers(push: false);
    }
    _controller.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      // 开启首次加载刷新
      firstRefresh: true,
      // 加载时的loading
      // 空视图、异常视图

      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _controller,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
            mainAxisExtent: MediaQuery.of(context).size.width / 1.6,
            //纵轴宽度比
            maxCrossAxisExtent: MediaQuery.of(context).size.width / 2,
            //横轴宽度比
            crossAxisSpacing: 2,
            //左右间隔
            mainAxisSpacing: 8,
            //上下间隔
            childAspectRatio: 1), //宽高比
        itemCount: _userList.length,
        itemBuilder: (BuildContext context, int index) {
          bool isEven = index.isEven; //是否是偶数
          double pl = isEven ? 18 : 9;
          double pr = isEven ? 9 : 18;
          return Container(
            color: Colors.white,
            padding: EdgeInsets.only(top: 16, left: pl, right: pr),
            child: SingerCard(
                coverPictureUrl: _userList[index].coverPictureUrl,
                nickName: _userList[index].nickname,
                musicCount: _userList[index].musicCount,
                musicPlayCount: _userList[index].musicPlayCount),
          );
        },
        padding: EdgeInsets.only(top: 8),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
